<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>淘好货 - 搜索结果</title>
    <script src="/static/css/tailwindcss.css"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF4400', // 主色调：橙色
                        secondary: '#FFB800', // 辅助色：黄色
                        dark: '#333333',    // 深色文本
                        light: '#F5F5F5',   // 浅色背景
                        muted: '#666666',   // 次要文本
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .product-card {
                @apply bg-white rounded-lg shadow-md overflow-hidden transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }

            .pagination-btn {
                @apply w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium transition-all duration-300;
            }

            .pagination-btn.active {
                @apply bg-primary text-white;
            }

            .pagination-btn:not(.active):hover {
                @apply bg-gray-100;
            }
        }
    </style>
</head>
<body class="bg-gray-50 text-dark">
<div id="app">
    <!-- 导航栏 -->
    <navigation></navigation>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-8">
        <section class="text-center mb-8">
            <h1 class="text-3xl font-bold mb-4">搜索结果</h1>
            <p class="text-gray-600">为您找到 <span
                    class="text-primary font-medium">{{ totalItems }}</span> 个结果</p>
        </section>

        <!-- 无搜索结果 -->
        <div v-if="products.length === 0" class="empty-cart bg-white rounded-lg shadow-md p-12">
            <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-20 w-20 text-primary/30" fill="none"
                 viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <p class="mt-4 text-lg text-gray-600">没有找到匹配的商品</p>
            <a href="/" class="mt-6 checkout-btn">返回首页</a>
        </div>

        <!-- 有搜索结果 -->
        <div v-else class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            <div v-for="product in products" :key="product.id" class="product-card">
                <div class="relative">
                    <a href="#" class="block">
                        <img :src="product.image" :alt="product.name" class="w-full h-48 object-cover">
                    </a>
                </div>
                <div class="p-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-2">
                        <a href="#"
                           class="hover:text-primary transition-colors line-clamp-2">{{ product.name }}</a>
                    </h3>
                    <div class="flex items-center justify-between">
                        <div>
                            <span class="text-primary font-bold text-lg">¥{{ product.price }}</span>
                        </div>
                        <button @click="addToCart(product.id)"
                                class="bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-lg transition-all flex items-center">
                            <i class="fa fa-shopping-cart mr-1"></i> 加入购物车
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分页条 -->
        <div v-if="totalPages > 1" class="flex justify-center mt-12">
            <div class="flex items-center space-x-1">
                <!-- 上一页 -->
                <button @click="prevPage" :disabled="currentPage == 1"
                        class="pagination-btn text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-left"></i>
                </button>

                <!-- 页码 -->
                <button v-for="page in totalPages" :key="page" @click="goToPage(page)"
                        :class="['pagination-btn', {'active': currentPage === page}]">
                    {{ page }}
                </button>

                <!-- 下一页 -->
                <button @click="nextPage" :disabled="currentPage == totalPages"
                        class="pagination-btn text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fa fa-angle-right"></i>
                </button>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <app-footer></app-footer>
</div>
</body>
<script src="/static/js/vue.js"></script>
<script src="/static/js/top.js"></script>
<script src="/static/js/foot.js"></script>
<script src="/static/js/common.js"></script>
<script src="/static/js/message.js"></script>
<script>
    // Vue实例
    new Vue({
        el: '#app',
        data: {
            util,
            products: [],
            kw: '',
            currentPage: 1,
            pageSize: 32,
            totalItems:0,
            totalPages:0,
        },
        methods: {
            // 添加到购物车
            async addToCart(productId) {
                try {
                    const data = {
                        'product_id': productId,
                        'quantity': 1,
                    }
                    const response = await fetch('/carts', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(data)
                    });
                    if (response.ok) {
                        message.success('添加成功')
                    } else {
                        const error = await response.json();
                        message.error(error);
                    }
                } catch (error) {
                    message.error('网络错误，请稍后重试');
                }
            },
            // 搜索功能
            async search() {
                try {
                    const response = await fetch(`/products?keyword=${this.kw}&page=${this.currentPage}&page_size=${this.pageSize}`);
                    if (response.ok) {
                        const res = await response.json();
                        this.products=res.data;
                        this.currentPage=res.pagination.current_page;
                        this.pageSize=res.pagination.page_size;
                        this.totalItems=res.pagination.total_items;
                        this.totalPages=res.pagination.total_pages;
                    } else {
                        const error = await response.json();
                        message.error(error.message);
                    }
                } catch (error) {
                    message.error('网络错误，请稍后重试');
                }
            },
            // 上一页
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.search();
                }
            },
            // 下一页
            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.search();
                }
            },
            // 跳转到指定页面
            goToPage(page) {
                if (page !== this.currentPage) {
                    this.currentPage = page;
                    this.search();
                }
            }
        },
        created() {
            util.store.set("return-url", location.href);
            if (this.util.isLogin()) {
                // 从URL参数获取搜索关键词
                const urlParams = new URLSearchParams(window.location.search);
                const query = urlParams.get('keyword');
                if (query) {
                    this.kw = query;
                    this.search()
                }
            } else location.href = '/login';
        }
    });
</script>
</html>